""" 

    Bills.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which takes a list of Ids and returns a list of the 6 most recent
    votes and how each legislator voted as a JSON object.
    
    Accepts two parameters:
        ids (required) - comma delimited list of Bioguide Ids
        offset (optional) - used for paging to get records 11-20, 21-30, etc.
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


from datetime import datetime
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from utils import fbUtil, memcacheUtil, textUtil, SunlightUtil
from xml.dom import minidom
import const
import facebook
import wsgiref.handlers
        

class MainHandler(webapp.RequestHandler):

    def get(self):
        self.post()
        
    def post(self):
           
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":"", "bills":[]}
        
        theIds = self.request.get('ids', default_value=None)
            
        if theIds is not None:
            
            newsCount = 6
            newsOffset = int(self.request.get('offset', default_value=0))
            memcache = memcacheUtil() 
            textutil = textUtil()
            legislatorIds = theIds.split(",")
            bills = {}
            sunlight = SunlightUtil(const.SUNLIGHT_API_KEY)
            memcacheutil = memcacheUtil()
            
            # get the info about extended permissions
            try:
                self.facebookapi = fbUtil().checkFacebookAppInstalled(self, False)
                if self.facebookapi is None:
                    jsonOutput["loggedin"] = False
                else:
                    jsonOutput["loggedin"] = True
                    jsonOutput["linkPermission"] = self.facebookapi.users.hasAppPermission("share_item")                
            except facebook.FacebookError, e:
                jsonOutput["loggedin"] = False
                
            for legislatorId in legislatorIds:
                
                legislator = sunlight.apicall("legislators.get", {"govtrack_id": legislatorId})
                if legislator is not None:
                    result = memcacheutil.getTextFromCache(const.GOVTRACK_BILL_API + legislatorId)
                    if result is not None:
                        xmlobj = minidom.parseString(result)
                        sponsoredBills = xmlobj.getElementsByTagName("SponsoredBills")
        
                        # get current legislator name and bioguide_id
                        current_legislator = {"name": const.FRIENDLY_NAME[legislator["legislator"]["bioguide_id"]], "id": legislator["legislator"]["bioguide_id"]}
                        
                        if len(sponsoredBills) > 0:
                            billsList = sponsoredBills[0].getElementsByTagName("Bill")
                            for billxml in billsList:
                                tempbill = {"name": current_legislator["name"], "id": current_legislator["id"]}
                                tempbill["session"] = billxml.getAttribute("Session")
                                tempbill["type"] = billxml.getAttribute("Type")
                                tempbill["number"] = billxml.getAttribute("Number")
                                tempbill["link"] = "http://www.opencongress.org/bill/" + const.CURRENT_CONGRESS + "-" + tempbill["type"] + tempbill["number"] + "/show"
                                tempbill["title"] = memcache.getTextFromXMLNode(billxml.getElementsByTagName("Title")[0].childNodes)
                                tempbill["description"] = memcache.getTextFromXMLNode(billxml.getElementsByTagName("OfficialTitle")[0].childNodes)
                                status = billxml.getElementsByTagName("Status")
                                tempdate = status[0].getAttribute("Date").split(" ")
                                tempdateNative = datetime.strptime(tempdate[0] + " " + tempdate[1] + " " + tempdate[2]  + " 00:00:00", "%b %d, %Y %H:%M:%S")
                                tempbill["time"] = textutil.timeAgo(None, None, tempdateNative)
                                tempbill["status"] = memcache.getTextFromXMLNode(status[0].childNodes)
                                bills[tempdateNative.strftime("%Y-%m-%d") + "_" + tempbill["session"] + "_" + tempbill["type"] + "_" + tempbill["number"]] = tempbill
                    

            keys = bills.keys()
            keys.sort(reverse=True)
            if keys is not None:
                
                if len(keys) < (newsCount+newsOffset):
                    newsCount = len(keys) - newsOffset
                
                for billIndex in range(newsCount):
                    if (billIndex + newsOffset) < len(keys):
                        jsonOutput["bills"].append(bills[keys[billIndex+newsOffset]])
                         

        else:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = "missing IDs"
                
                       
        self.response.out.write(simplejson.dumps(jsonOutput))    
        
        
def main():
    application = webapp.WSGIApplication([('/fb/bills', MainHandler)],
                                       debug=True)
    run_wsgi_app(application)
                                       

if __name__ == '__main__':
    main()
